package com.example.administrator.hqq.fragment.information;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.example.administrator.hqq.R;
import com.example.administrator.hqq.View.layout.EmptyLayout;
import com.example.administrator.hqq.adapter.information.NotificationListAdapter;
import com.example.administrator.hqq.base.MyFragemnt;
import com.example.administrator.hqq.bean.UmengMesssage;
import com.example.administrator.hqq.bean.event.InformationEvent;
import com.example.administrator.hqq.config.LoongsConfig;
import com.example.administrator.hqq.config.UrlFactory;
import com.example.administrator.hqq.fragment.MineFragment;
import com.example.administrator.hqq.utils.HintWordsUtils;
import com.google.gson.Gson;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.rong.imkit.RongIM;
import io.rong.imlib.model.Conversation;
import okhttp3.Call;

/**
 * A simple {@link Fragment} subclass.
 */
public class NotificationFragment extends MyFragemnt {

    @BindView(R.id.list_view)
    ListView listView;
    Unbinder unbinder;
    @BindView(R.id.SmartRefreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.empty)
    EmptyLayout empty;
    private String TAG = this.getClass().getSimpleName();
    private List<UmengMesssage.DataBean> data;
    private NotificationListAdapter notificationListAdapter;
    private MineFragment.AddModule addModule;

    public NotificationFragment() {
        // Required empty public constructor
    }

    public void setAddModule(MineFragment.AddModule addModule) {
        this.addModule = addModule;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_notification, container, false);
        unbinder = ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);
        initView();
        initData();
        return view;
    }

    private void initView() {
        data = new ArrayList<>();
        notificationListAdapter = new NotificationListAdapter(getContext(), data);
        listView.setAdapter(notificationListAdapter);
        //设置刷新动画
        refreshLayout.setEnableAutoLoadMore(false);
        refreshLayout.setRefreshHeader(new MaterialHeader(getContext()));
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                //下拉刷新
                initData();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                //上拉加载
                initData();
            }
        });
        notificationListAdapter.setNotificationOnClike(new NotificationListAdapter.NotificationOnClike() {
            @Override
            public void consent(int position) {
                acceptJoinGroup(position);
            }

            @Override
            public void refuse(int position) {
                denyJoinGroup(position);
            }

            @Override
            public void jumpGroup(int position) {
                if ("JUMP_GROUP".equals(data.get(position).getType())) {
                    LoongsConfig.getUsersIdSPUtils().put(LoongsConfig.Conversation.ChatConversationType, LoongsConfig.Conversation.GROUP);
                    LoongsConfig.getUsersIdSPUtils().put(LoongsConfig.Conversation.ConversationID, data.get(position).getGroup_id());
                    RongIM.getInstance().startConversation(getContext(), Conversation.ConversationType.GROUP, data.get(position).getGroup_id(), "话圈圈");
                }

            }

            @Override
            public void jumpTopic(int position) {
                if ("JUMP_TOPIC".equals(data.get(position).getType())) {
                    if (addModule != null) {
                        addModule.addModule(data.get(position).getCategory_id());
                    }
                }
            }
        });
    }

    /**
     * 同意加群
     *
     * @param position
     */
    private void acceptJoinGroup(final int position) {
        showLoadingDialog();
        OkHttpUtils.get().url(UrlFactory.acceptJoinGropNotice())
                .addParams(LoongsConfig.application_id, data.get(position).getApplication_id())
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "同意加群onError: " + e.getMessage());
                dismissLoadingDialog();
            }

            @Override
            public void onResponse(String response, int id) {
                dismissLoadingDialog();
                Log.e(TAG, "同意加群onResponse: " + response);
                try {

                    JSONObject jsonObject = new JSONObject(response);
                    HintWordsUtils.showMarkeWords(jsonObject.getInt(LoongsConfig.code), jsonObject.getString(LoongsConfig.description));
                    int code = jsonObject.getInt(LoongsConfig.code);
                    if (code == 200) {
                        initData();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 拒绝加群
     *
     * @param position
     */
    private void denyJoinGroup(final int position) {
        showLoadingDialog();
        OkHttpUtils.get().url(UrlFactory.denyJoinGropNotice())
                .addParams(LoongsConfig.application_id, data.get(position).getApplication_id())
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                dismissLoadingDialog();
                Log.e(TAG, "同意加群onError: " + e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                dismissLoadingDialog();
                Log.e(TAG, "同意加群onResponse: " + response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    int code = jsonObject.getInt(LoongsConfig.code);
                    if (code == 200) {
                        initData();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void initData() {
        OkHttpUtils.get().url(UrlFactory.ListNotice())
                .addParams(LoongsConfig.user_id, LoongsConfig.getUser_id())
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "通知列表onError:  " + e);
                if (empty!=null)
                    empty.showEmpty(R.drawable.empty_image,"暂无更多通知");
            }

            @Override
            public void onResponse(String response, int id) {
                if (refreshLayout != null) {
                    refreshLayout.finishRefresh();
                    refreshLayout.finishLoadMore();
                }
                Log.e(TAG, "通知列表onResponse: " + response);
                Gson gson = new Gson();
                UmengMesssage umengMesssage = gson.fromJson(response, UmengMesssage.class);
                if (umengMesssage.getCode() == 200) {
                    data.clear();
                    data.addAll(umengMesssage.getData());
                    notificationListAdapter.notifyDataSetChanged();

                }
                if (data==null||data.size()==0){
                    empty.showEmpty(R.drawable.empty_image,"暂无消息内容");
                }
                else{
                    empty.hide();
                }
            }
        });
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(InformationEvent informationEvent) {
        if ("NOTIFICATION".equals(informationEvent.getType())) {
            initData();
        }
    }
}
